<template>
  <el-card class="box-card">
    <template #header>修改密码</template>
    <el-form
      :model="passFrom"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="原密码" prop="oldpewd">
        <el-input
          type="password"
          v-model="passFrom.oldpewd"
          autocomplete="off"
          @blur="oldpwd"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          type="password"
          v-model="passFrom.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="checkpwd">
        <el-input
          type="password"
          v-model="passFrom.checkpwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          :loading="load"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { validatePass, validateNewPass, validateNewPass2 } from '@/utils/rule'
import { verificationpwd, editpwd } from '../../api/user'
import local from '../../utils/local.js'
export default {
  data() {
    return {
      // 数据对象
      passFrom: {
        oldpewd: '',
        password: '',
        checkpwd: ''
      },
      // 规则对象
      rules: {
        oldpewd: [{ validator: validatePass, trigger: 'blur' }],
        password: [{ validator: validateNewPass(this), trigger: 'blur' }],
        checkpwd: [{ validator: validateNewPass2(this), trigger: 'blur' }]
      },
      stauts: false,
      load: false
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.load = true
          if (!this.stauts) return this.$message.error('原密码错误!!')
          const { code, msg } = await editpwd({
            newPwd: this.passFrom.password
          })
          if (code === 0) {
            this.$message.success(msg)
            local.cls()
            setTimeout(() => {
              // 刷新页面
              location.reload()
            }, 2000)
          } else {
            this.$message.error(msg)
          }
        } else {
          console.log('error submit!!')
          setTimeout(() => {
            this.load = false
          }, 1000)
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    async oldpwd() {
      const { code, msg } = await verificationpwd({
        oldPwd: this.passFrom.oldpewd
      })
      if (code === '00') {
        this.stauts = true
        this.$message.success(msg)
      } else {
        this.stauts = false
        this.$message.error(msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 370px;
}
</style>
